﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace MvcWeb.Controllers
{
    public class UserController : BaseController
    {
        // GET: /User/
        public ActionResult Index()
        {
            
            return View();
        }

        public ActionResult List(int? id = 0)
        {
            var list = db.User_Profiles.Where(m => m.DeptId == id).ToList();
            var userDict = db.aspnet_Users.Select(m => new { m.UserId, m.UserName }).ToDictionary(a => a.UserId, b => b.UserName);
            var deptDict = db.User_Depts.Select(m => new { m.Id, m.Name }).ToDictionary(a => a.Id, b => b.Name);

            List<MvcWeb.ViewModels.User.UserModel> viewModel = new List<ViewModels.User.UserModel>();
            int deptId = 0;
            string userName = null, deptName = null;
            string[] roleList = null;
            foreach (var m in list)
            {
                deptId = m.DeptId ?? 0;
                userName = userDict.ContainsKey(m.UserId) ? userDict[m.UserId] : null;
                deptName = deptDict.ContainsKey(deptId) ? deptDict[m.DeptId ?? 0] : null;
                roleList = Roles.GetRolesForUser(userName);

                viewModel.Add(new ViewModels.User.UserModel()
                {
                    UserId = m.UserId,
                    UserName = userName,
                    RealName = m.RealName,
                    DeptId = deptId,
                    DeptName = deptName,
                    RoleList = roleList
                });
            }

            return View(viewModel);
        }

        public ActionResult Edit(string id, int? deptId = 0)
        {
            MvcWeb.ViewModels.User.UserModel viewModel = new ViewModels.User.UserModel();
            viewModel.DeptId = deptId ?? 0;

            if (!string.IsNullOrWhiteSpace(id))
            {
                Guid guid = new Guid(id);
                var user = db.aspnet_Users.Find(guid);
                var profile = db.User_Profiles.Find(guid);

                if (user != null)
                {
                    viewModel.UserName = user.UserName;
                }

                if (profile != null)
                {
                    viewModel.RealName = profile.RealName;
                    viewModel.DeptId = profile.DeptId ?? 0;
                    viewModel.RoleList = Roles.GetRolesForUser(viewModel.UserName);
                }
            }

            viewModel.AllRoleList = Roles.GetAllRoles();

            return View(viewModel);
        }

        [HttpPost]
        public ActionResult Edit(string id, MvcWeb.ViewModels.User.UserModel viewModel, int? deptId = 0)
        {
            string roleStr = Request.Form["roleName"];
            string[] roleArr = null;
            if (string.IsNullOrWhiteSpace(id))
            {
                bool exist = Membership.FindUsersByName(viewModel.UserName).Count > 0;
                if (exist)
                {
                    viewModel.Error = "登录名已存在";
                    viewModel.AllRoleList = Roles.GetAllRoles();
                    return View(viewModel);
                }

                //创建帐号
                string defaultPwd = ConfigurationManager.AppSettings["DefaultPwd"];
                var user = Membership.CreateUser(viewModel.UserName, "666666");

                //添加角色
                if (!string.IsNullOrWhiteSpace(roleStr))
                {
                    roleArr = roleStr.Split(',');
                    Roles.AddUserToRoles(user.UserName, roleArr);
                }

                //添加关联信息
                EAM.Model.User_Profile profile = new EAM.Model.User_Profile() 
                { 
                    UserId = new Guid(user.ProviderUserKey.ToString()),
                    RealName = viewModel.RealName,
                    DeptId = viewModel.DeptId
                };
                db.User_Profiles.Add(profile);
            }
            else
            {
                var profile = db.User_Profiles.Find(new Guid(id));
                db.User_Profiles.Attach(profile);
                profile.DeptId = viewModel.DeptId;
                profile.RealName = viewModel.RealName;

                var user = db.aspnet_Users.Find(profile.UserId);
                roleArr = Roles.GetRolesForUser(user.UserName);
                if (roleArr != null && roleArr.Length > 0)
                {
                    Roles.RemoveUserFromRoles(user.UserName, Roles.GetRolesForUser(user.UserName));
                }
                if (!string.IsNullOrWhiteSpace(roleStr))
                {
                    roleArr = roleStr.Split(',');
                    Roles.AddUserToRoles(user.UserName, roleArr);
                }
            }
            db.SaveChanges();

            return RedirectToAction("List", new { id = deptId });
        }

        public ActionResult Exist(string userName)
        {
            bool exist = Membership.FindUsersByName(userName).Count > 0;
            return Json(!exist, JsonRequestBehavior.AllowGet);
        }

        public ActionResult ResetPwd(string id)
        {
            var user = Membership.GetUser(id);
            string pwd = user.ResetPassword();
            string defaultPwd = ConfigurationManager.AppSettings["DefaultPwd"];
            user.ChangePassword(pwd, defaultPwd);
            return View();
        }

        public ActionResult ChangePwd()
        {

            return View();
        }

        [HttpPost]
        public ActionResult ChangePwd(MvcWeb.ViewModels.Home.ChangePasswordModel viewModel)
        {
            var user = Membership.GetUser();
            if (!Membership.ValidateUser(user.UserName, viewModel.OldPwd))
            {
                viewModel.Messages = "旧密码错误";
                return View(viewModel);
            }

            user.ChangePassword(viewModel.OldPwd, viewModel.NewPwd);
            viewModel.Messages = "修改密码成功";

            return View(viewModel);
        }
    }
}
